<template>
    <el-select
        v-model="formData[prop]"
        v-bind="$attrs"
        :placeholder="placeholder"
        :clearable="clearable"
        :filterable="filterable"
        :collapse-tags="collapseTags"
        :collapse-tags-tooltip="collapseTagsTooltip"
        @change="doChange"
        @focus="doFocus"
    >
        <el-checkbox
            v-if="$attrs.multiple && $attrs.isCanSelectALL"
            :value="selectAll"
            style="padding-left: 20px"
            @change="doSelectAll"
            >全选</el-checkbox
        >
        <el-option
            v-for="(item, index) in $attrs.options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"
        >
        </el-option>
    </el-select>
</template>

<script>
export default {
    props: {
        formData: {
            type: Object,
            default: () => ({})
        },
        prop: {
            type: String,
            default: ''
        },
        onChange: {
            type: [Function, undefined],
            default: undefined
        },
        onFocus: {
            type: [Function, undefined],
            default: undefined
        },
        onSelectAll: {
            type: [Function, undefined],
            default: undefined
        },
        placeholder: {
            type: String,
            default: '请选择'
        },
        clearable: {
            type: Boolean,
            default: true
        },
        filterable: {
            type: Boolean,
            default: true
        },
        collapseTags: {
            type: Boolean,
            default: true
        },
        collapseTagsTooltip: {
            type: Boolean,
            default: true
        }
    },
    computed: {
        selectAll() {
            return (
                this.$attrs.multiple &&
                typeof this.formData[this.prop] === 'object' &&
                this.$attrs.options.every((i) =>
                    this.formData[this.prop].includes(i.value)
                )
            )
        }
    },
    methods: {
        doChange(e) {
            if (this.onChange) {
                this.onChange(e)
            }
        },
        doFocus(e) {
            if (this.onFocus) {
                this.onFocus(e)
            }
        },
        doSelectAll(e) {
            const list = []
            if (e) {
                this.formData[this.prop] = this.$attrs.options.forEach((i) => {
                    list.push(i.value)
                })
            }
            this.formData[this.prop] = list
            if (this.onSelectAll) {
                this.onSelectAll(e)
                return
            }
        }
    }
}
</script>

<style></style>
